package com.fingard.dsp.bank.directbank.bjums01;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;

/**
 * 北京银商对账单
 */
public class BJUMS01Statement extends BJUMS01Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpPosRecRespHeader = getPosRecStatement(p_reqQrySttm, retAts);
        String tmpPosRecTotalNum = retAts.totalNum;
        if ("".equals(tmpPosRecTotalNum)) {
            tmpPosRecTotalNum = "0";
        }

        if ("-1".equals(tmpPosRecRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("POS对账单获取失败,原因:" + tmpPosRecRespHeader[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = tmpPosRecRespHeader[1];

                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            }

            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpPosRecTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }

    /**
     * POS对账单
     *
     * @param p_reqQrySttm
     * @param retAts
     * @return
     * @throws Exception
     */
    private String[] getPosRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;

        try {

            FtpSet ftpSet = bankFront.getFtpSet("pos");
            ftpSet.downDir = StringHelper.trimEnd(ftpSet.getDownDir("pos"), "/") + "/" + p_reqQrySttm.busDate;
            WriteBankLogLn2("北京银商POS对账单FTP服务器地址:" + ftpSet.serverIP + ":" + ftpSet.port);

            StringBuilder sbFileContent = new StringBuilder();

            String tmpPosMode = getBankConfig().getValueAsString("posRecUseVersion");

            if ("A".equals(tmpPosMode)) {
                String useNewFormat = getBankConfig().getValueAsString("useNewFormatA");
                String downFileName = "";
                String[] provinceArray = null;
                String provinceList = getBankConfig().getValueAsString("provinceList");
                if (provinceList.contains(",")) {
                    provinceArray = provinceList.split(",");
                }
                for (String tmpProvince : provinceArray) {
                    if ("true".equals(useNewFormat.toLowerCase())) {
                        downFileName = getBankConfig().getValueAsString("merchantId") + "_" + p_reqQrySttm.actNum + "_" + p_reqQrySttm.busDate + ".txt";
                    } else {
                        downFileName = getBankConfig().getValueAsString("merchantId") + p_reqQrySttm.busDate + tmpProvince + ".txt";
                    }

                    WriteBankLogLn2("北京银商POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

                    String localFilePath = createTempFileDirectory() + File.separator + downFileName;
                    WriteBankLogLn2("北京银商POS对账单保存本地路径:" + localFilePath);

                    FtpReceiver ftpReceiver = null;
                    String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
                    if ("ftp".equals(posRecRequestType.toLowerCase())) {
                        FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                        ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
                    } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                        WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                        ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, localFilePath);
                    }
                    if (ftpReceiver.isCompleted) {
                        if (sbFileContent.length() > 0) {
                            sbFileContent.append("\n");
                        }
                        sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "北京银商POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                    }
                }
            } else if ("C".equals(tmpPosMode)) {
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.getDownDir("pos"), "/");
                String useNewFormat = getBankConfig().getValueAsString("useNewFormatC");
                String downFileName = "";
                String[] provinceArray = getBankConfig().getValueAsString("provinceList").split(",");
                for (String tmpProvince : provinceArray) {
                    if ("true".equals(useNewFormat.toLowerCase())) {
                        downFileName = getBankConfig().getValueAsString("merchantId") + "_" + getBankConfig().getValueAsString("merchantNO") + "_" + p_reqQrySttm.busDate + ".txt";
                    } else {
                        downFileName = getBankConfig().getValueAsString("merchantId") + p_reqQrySttm.busDate + tmpProvince + ".txt";
                    }

                    WriteBankLogLn2("北京银商POS对账单所在服务器路径:" + ftpSet.downDir + "/" + downFileName);

                    String localFilePath = createTempFileDirectory() + File.separator + downFileName;
                    WriteBankLogLn2("北京银商POS对账单保存本地路径:" + localFilePath);

                    FtpReceiver ftpReceiver = null;
                    String posRecRequestType = getBankConfig().getValueAsString("posRecRequestType");
                    if ("ftp".equals(posRecRequestType.toLowerCase())) {
                        FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                        ftpReceiver = ftpPortClient.downloadFile(downFileName, localFilePath);
                    } else if ("sftp".equals(posRecRequestType.toLowerCase())) {
                        SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                        String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + downFileName;
                        WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                        ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, localFilePath);
                    }
                    if (ftpReceiver.isCompleted) {
                        if (sbFileContent.length() > 0) {
                            sbFileContent.append("\n");
                        }
                        sbFileContent.append(FileHelper.readFileText(localFilePath, getCharset("UTF-8", "pos")));
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "北京银商POS对账单下载失败,原因:\r\n" + ftpReceiver.connMsg;
                    }
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "对账单版本错误,当前版本为:[" + tmpPosMode + "].";
            }
            if (StringHelper.hasAnyChar(sbFileContent.toString())) {
                tmpRespCode = "0";

                String tmpStrRet = sbFileContent.toString();
                WriteBankLogLn2("北京银商POS对账单响应数据:\r\n" + tmpStrRet);

                StringReader strReader = new StringReader(tmpStrRet);
                BufferedReader tmpReader = new BufferedReader(strReader);

                boolean isContinue = false;
                while (true) {
                    String eachline = tmpReader.readLine();
                    if (eachline == null) {
                        break;
                    }
                    if ("".equals(eachline.trim())) {
                        continue;
                    }

                    String[] detailNodes = eachline.split("`~");
                    if (p_reqQrySttm.actNum.equals(detailNodes[1].trim())) {
                        totalNum++;
                        isContinue = true;
                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                        if (StringHelper.hasAnyChar(detailNodes[4])) {
                            tmpRetDetail.askNumber = detailNodes[4].trim();
                        }

                        tmpRetDetail.cdFlag = "22";

                        if (StringHelper.hasAnyChar(detailNodes[11])) {
                            tmpRetDetail.amount = StringHelper.amountDivide100(detailNodes[11].trim());
                        }

                        if (StringHelper.hasAnyChar(detailNodes[15])) {
                            tmpRetDetail.fee = StringHelper.amountDivide100(detailNodes[15].trim());
                        }

                        tmpRetDetail.busTime = detailNodes[6];

                        if (StringHelper.hasAnyChar(detailNodes[7])) {
                            tmpRetDetail.oppAct = detailNodes[7].trim();
                        }

                        if (StringHelper.hasAnyChar(detailNodes[8])) {
                            tmpRetDetail.oppActName = detailNodes[8].trim();
                        }

                        if ("2".equals(detailNodes[13].trim())) {
                            tmpRetDetail.transState = TransState.Success;
                        } else {
                            tmpRetDetail.transState = TransState.Fail;
                        }

                        retAts.writeRetDetail(tmpRetDetail);
                    }
                }

                if (!isContinue) {
                    tmpRespCode = "0";
                    tmpRespInfo = "没有符合条件的记录!";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }
}
